package tests;

import java.util.Random;

import ar.edu.itba.pod.printer.Document;
import ar.edu.itba.pod.printer.PrinterDispatcher;
import ar.edu.itba.pod.printer.impl.EnhancedPoolPrinterDispatcher;
import ar.edu.itba.pod.printer.impl.MyThread;

public class SimpleAsynTest7 {
	
	public static void main(String[] args) {
		
		final int PRUBES = 10;
		long time=0;
		
		System.out.println( "ej 7.2c\n ENHANCE POOL PRINTER DISPATCHER");
		
		for(int i=0; i<PRUBES;i++){
			time+=fiftyRequest();
			System.out.println("prueba terminada");
		}
		System.out.println( "Tiempo Promedio:" +  time/PRUBES );
	}
	
	
	public static long fiftyRequest(){
		final int PRINT_REQUEST = 50;
		final int PAGES = 100;
		final String DOC_NAME = "name";
		final Random random = new Random();
		
		long start= System.currentTimeMillis();
		final PrinterDispatcher dispatcher = new EnhancedPoolPrinterDispatcher(10);
		
		MyThread printersThread = new MyThread() {
			
			@Override
			public void excecute() {
					try {
						sleep(1000);
						if(random.nextBoolean()){
							((EnhancedPoolPrinterDispatcher)dispatcher).removePrinter();
						} else {
							((EnhancedPoolPrinterDispatcher)dispatcher).addPrinter();
						}
					} catch (InterruptedException e) {
						//
						//e.printStackTrace();
						System.out.println("ejecucion de thread impresora finalizado");
					}
			}
		};
	
		printersThread.start();
		
		for(int r=0;r < PRINT_REQUEST; r++){
			Document document=new Document(PAGES*random.nextInt(15), true, DOC_NAME);
			dispatcher.printDocument(document);
			System.out.print('.');
			try {
				Thread.sleep(500);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		
		printersThread.finish();
		dispatcher.finishPrintRequests();
		
		return System.currentTimeMillis()-start;
		
	}

}
